package cn.stacey.webday02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoLog extends HttpServlet{
//	private String logFile;
//	private String dateFormat;
//	每次只用new 一个writer  变成全局变量，不需要每次都new 
	private BufferedWriter writer;
	private DateFormat fommater;
	@Override
	public void init() throws ServletException {
		// 获取到web.xml中的初始化参数name value
		ServletConfig config=getServletConfig(); 
		String logFile=config.getInitParameter("logFile");
		String dateFormat=config.getInitParameter("dateFormat");
		try {
			writer=new BufferedWriter(new FileWriter(logFile,true));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		fommater=new SimpleDateFormat(dateFormat);
		super.init();
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println(req.getRemoteAddr());
		Date date=new Date();
//		DateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		System.out.println(format);
		String context=req.getRemoteAddr()+"\t"+fommater.format(date);
		logfile(context);
	}
	//需要同步，每次来一个请求，几个线程同时访问一个资源会有问题
	private synchronized void logfile(String context) {
		//或者synchronized(this)
//		(BufferedWriter writer=new BufferedWriter(new FileWriter("E:\\access.log",true));)
//	 在init中初始化logFile之后（定义全局变量BufferedWriter writer）就不需要每次都在logfile方法中new 
		try {
			
			writer.write(context);
			writer.write("\r\n");
			writer.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}
	@Override
	
		public void destroy() {
		if(writer!=null) {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		}

}